/*
 * This is the Socket Client
 */
package SocketDemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    private Socket socket;

    public Client() {
        try {
            this.socket = new Socket("localhost", 8080);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Client(String host, int port) {
        try {
            this.socket = new Socket(host, port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void send(String info) {
        try {
            PrintWriter writer = new PrintWriter(socket.getOutputStream());
            writer.print(info);
            writer.flush();
            System.out.println("Client:     Send MSG to Server: " + info);
            socket.shutdownOutput();

            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String temp = null;
            String message = "";
            while ((temp = reader.readLine()) != null) {
                message += temp;
                System.out.println("Client:     Recv MSG From Server: " + message);
            }

            writer.close();
            reader.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
